package com.gdou.teaching.converter;

import com.gdou.teaching.Enum.ResultEnum;
import com.gdou.teaching.Enum.UserIdentEnum;
import com.gdou.teaching.Enum.UserStatusEnum;
import com.gdou.teaching.dataobject.User;
import com.gdou.teaching.exception.TeachingException;
import com.gdou.teaching.form.UserInPutObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author carrymaniac
 * @date Created in 18:47 2019-08-15
 * @description 用户类VO的List转换为User的List
 **/
@Slf4j
public class UserInPutObjectConverter {
     public static List<User> UserInPutObjectListConvert2UserList(List<UserInPutObject> userInPutObjectList, Integer clazzId, UserIdentEnum userIdentEnum) {
        List<User> userList = userInPutObjectList.stream().map(userInPutObject -> {
            User user = new User();
            user.setClassId(clazzId);
            user.setNickname(userInPutObject.getNickName());
            user.setUserNumber(userInPutObject.getUserNumber());
            user.setUserStatus(UserStatusEnum.NORMAL.getCode());
            user.setUserIdent(userIdentEnum.getCode());
            String salt = UUID.randomUUID().toString().substring(0, 5);
            user.setSalt(salt);
            user.setHeadUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
            user.setPassword(DigestUtils.md5DigestAsHex((userInPutObject.getUserNumber() + salt).getBytes()));
            return user;
        }).collect(Collectors.toList());
        return userList;
    }


    public static  List<UserInPutObject> String2ObjectList(String UserInPutObjectString) {
        List<UserInPutObject> userInPutObjectListList;
        try {
            Gson gson = new Gson();
            userInPutObjectListList = gson.fromJson(UserInPutObjectString, new TypeToken<List<UserInPutObject>>() {
            }.getType());
        } catch (Exception e) {
            log.error("[对象转换]错误，String={}", UserInPutObjectString);
            throw new TeachingException(ResultEnum.PARAM_ERROR);
        }
        return userInPutObjectListList;
    }

}
